/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 广告发布中心
 */
import React, { useMemo, useRef, useCallback, useState } from 'react';
import { Popconfirm, Button, Space } from 'antd';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { debounce } from 'lodash';
import { PlusOutlined } from '@ant-design/icons';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import { getAdvList, deleteAdv, online } from '@/services/operatorManagement';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { AdvTableListItem } from '../types/Advertisements';
import AdvEdit from './AdvEdit';

const AdvRelease: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [record, setRecord] = useState<AdvTableListItem>({} as any);
  const [editType, setEditType] = useState<'add' | 'edit'>('add');
  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [onLineLoading, setOnLineLoading] = useState<boolean>(false);
  const [loadingID, setLoadingID] = useState<string>('');
  const formRef = useRef<ActionType>();

  const deleteAdvs = useCallback((id: string) => {
    deleteAdv({ id }).then(() => {
      formRef.current?.reload();
    });
  }, []);

  const goOnline = useCallback(
    debounce(
      (id: string, status: string) => {
        setOnLineLoading(true);
        setLoadingID(id);
        online({ id, status }).then(() => {
          setOnLineLoading(false);
          setLoadingID('');
          formRef.current?.reload();
        });
      },
      300,
      {
        trailing: false,
        leading: true,
      },
    ),
    [],
  );

  const onAddClick = useCallback(() => {
    setEditVisible(true);
    setEditType('add');
  }, []);

  const onEditClick = useCallback((records: AdvTableListItem) => {
    setRecord(records);
    setEditType('edit');
    setEditVisible(true);
  }, []);

  const columns: ProColumns<AdvTableListItem>[] = useMemo(
    () => [
      {
        title: '序号',
        width: 80,
        dataIndex: 'id',
        align: 'center',
        search: false,
      },
      {
        title: '创建时间',
        width: 150,
        dataIndex: 'created_at',
        align: 'center',
        search: false,
      },
      {
        title: '广告名称',
        width: 150,
        dataIndex: 'name',
        align: 'center',
      },
      {
        title: '平台类型',
        width: 150,
        dataIndex: 'status',
        align: 'center',
        valueType: 'select',
        initialValue: '1',
        search: false,
        render: () => '线下',
        fieldProps: {
          options: [
            {
              label: '线下',
              value: '1',
            },
          ],
        },
      },
      {
        title: '广告平台',
        width: 150,
        dataIndex: 'platform',
        align: 'center',
        valueType: 'select',
        render: (_, item) => (item.platform === '1' ? '面单' : '取件码'),
        fieldProps: (form) => ({
          options: [
            {
              label: '面单',
              value: '1',
            },
            {
              label: '取件码',
              value: '2',
            },
            {
              label: '一联单',
              value: '3',
            },
          ],
          onChange: () => {
            form.setFieldsValue({
              brand: undefined,
            });
          },
        }),
      },
      {
        title: '广告位置',
        width: 150,
        dataIndex: 'brand',
        align: 'center',
        valueType: 'select',
        render: (_, item) => {
          const { brand, platform } = item;
          const brandMap = {
            kb: '快宝面单',
            cn: '菜鸟面单',
          };
          return platform === '2' ? '快宝取件码' : brandMap[brand];
        },
        fieldProps: (form) => {
          const platform = form?.getFieldValue('platform');
          switch (platform) {
            case '1':
              return {
                options: [
                  {
                    label: '快宝面单',
                    value: 'kb',
                  },
                  {
                    label: '菜鸟面单',
                    value: 'cn',
                  },
                ],
              };
            case '2':
              return {
                options: [
                  {
                    label: '快宝取件码',
                    value: 'kb',
                  },
                ],
              };
            case '3':
              return {
                options: [
                  {
                    label: '快宝面单',
                    value: 'kb',
                  },
                ],
              };
            default:
              return {
                options: [],
              };
          }
        },
      },
      {
        title: '创建人',
        width: 150,
        dataIndex: 'creator',
        align: 'center',
        search: false,
      },
      {
        title: '操作',
        width: winSize === 'xs' ? 100 : 180,
        align: 'center',
        search: false,
        fixed: 'right',
        render: (_, item) => {
          const { is_plan, status, id } = item;
          return (
            <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
              <Button
                key='0'
                type='primary'
                disabled={is_plan == '1' || status === '3'}
                onClick={() => goOnline(id, status == '1' ? '2' : '1')}
                loading={loadingID === id && onLineLoading}
                size='small'
              >
                {status === '2' ? '上线' : '下线'}
              </Button>
              <Button
                key='1'
                type='primary'
                onClick={() => onEditClick(item)}
                disabled={status === '1' || status === '3'}
                size='small'
              >
                编辑
              </Button>
              <Popconfirm
                key='2'
                title='确定删除该条广告？'
                onConfirm={() => deleteAdvs(id)}
                disabled={is_plan == '1' || status === '3' || status === '1'}
              >
                <Button
                  type='primary'
                  danger
                  disabled={is_plan == '1' || status === '3' || status === '1'}
                  size='small'
                >
                  删除
                </Button>
              </Popconfirm>
            </Space>
          );
        },
      },
    ],
    [onLineLoading, loadingID, deleteAdvs, goOnline, onEditClick, winSize],
  );

  const getTableList = useCallback((params) => {
    const { current: page, pageSize, ...rest } = params;
    return getAdvList({ page, pageSize, ...rest });
  }, []);

  const onClose = useCallback(() => {
    setEditVisible(false);
    setRecord({} as any);
  }, []);

  return (
    <>
      <DragTable>
        <ProTable<AdvTableListItem>
          className='kb-pro-table'
          actionRef={formRef}
          rowKey='id'
          columns={columns}
          options={false}
          request={getTableList}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            optionRender: (searchConfig, formProps, dom) => [
              ...dom.reverse(),
              <Button key='add' onClick={onAddClick} type='primary'>
                <PlusOutlined />
                发布新广告
              </Button>,
            ],
          }}
          pagination={{
            pageSize: 20,
            showSizeChanger: false,
          }}
          scroll={{ x: 800 }}
        />
      </DragTable>

      <AdvEdit
        type={editType}
        visible={editVisible}
        record={record}
        onClose={onClose}
        getList={() => formRef.current?.reload()}
      />
    </>
  );
};

export default AdvRelease;
